/**
 * 
 */
package se.cirrus.base;

import java.io.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.LogManager;
import java.util.logging.Logger;

import se.cirrus.base.struct.ChatContent;
import se.cirrus.base.struct.Content;
import se.cirrus.base.struct.SystemContent;

/**
 * @author Winquman
 *
 */
public class ChatProgram {

	String name, current, wqueue;
	Logger log;
	ConcurrentLinkedQueue<Content> upQ, downQ;
	
	public ChatProgram(ConcurrentLinkedQueue<Content> down, ConcurrentLinkedQueue<Content> up) {
		log = LogManager.getLogManager().getLogger("ALL");
		
		log.fine("ChatProgram initialized logging!");
		
		upQ = up;
		downQ = down;
	}
	
	
	public void interfaceLoop() {
		
		log.finer("Now entering interfaceLoop() for first time.");
		
		BufferedReader br;
		br = new BufferedReader(new InputStreamReader(System.in));
		
		System.out.println("\n\n\n\nCIRRUS-CHAT");
		System.out.print("Name: ");
		try {
			name = br.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			name = "Unknown";
		}
		
		log.finer("User name is " + name);
		
		while(true) {
			log.finest("Looping chat interface.");
			
			System.out.print(name + ">");
			try {
				current = br.readLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if(current.startsWith("/exit")) {
				log.info("Recieved EXIT from user, shutting down gracefully...");
				checkQ();
				System.out.println(wqueue);
				return;
			}
		
			log.finest("Will send current data.");
			sendCurrent();
			
			log.finest("Will check upQ for new data.");
			checkQ();
			
			log.finest("Printing possible new data.");
			System.out.println(wqueue);
		}
	}
	
	
	private void sendCurrent() {
		if(current.startsWith("/")) {
			log.finer("User supplied a system command: " + current);
			
			downQ.add(new SystemContent(current));
		} else {
			downQ.add(new ChatContent(name,current));
		}
	}
	
	private void checkQ() {
		Content c;
		
		while(!upQ.isEmpty()) {
			c = upQ.remove();
			wqueue = c.toString() + "\n";
		}
	}
}
